<?php

namespace App\Models;

use App\Models\User;

class UserThirdPartyBind extends Model
{
    protected $fillable = ['uid', 'platform', 'openid', 'unionid', 'session_key', 'nickname', 'info'];

    protected $casts = [
        'info' => 'json',
    ];

    const PLATFORM_QQ = 'qq';
    const PLATFORM_WEIXIN_OPEN = 'weixin.open';

    public function user()
    {
        return $this->belongsTo(User::class, 'uid');
    }

    public function scopePlatformWeixinOpen($query)
    {
        return $query->where('platform', self::PLATFORM_WEIXIN_OPEN);
    }

    public function scopePlatformQQ($query)
    {
        return $query->where('platform', self::PLATFORM_QQ);
    }

    public static function createByQQ(array $info)
    {
        return static::create([
            'platform' => static::PLATFORM_QQ,
            'uid' => $info['uid'] ?? 0,
            'openid' => $info['openid'],
            'unionid' => $info['unionid'] ?? '',
            'nickname' => $info['nickname'] ?? '',
            'info' => $info,
        ]);
    }

    public static function createByWeixinOpen(array $info)
    {
        return static::create([
            'platform' => static::PLATFORM_WEIXIN_OPEN,
            'uid' => $info['uid'] ?? 0,
            'openid' => $info['openid'],
            'unionid' => $info['unionid'] ?? '',
            'nickname' => $info['nickname'] ?? '',
            'info' => $info,
        ]);
    }
}
